package com.zhongkai.service.config;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.zhongkai.dao.config.ActionDAO;
import com.zhongkai.model.config.User;
import com.zhongkai.service.BaseService;

@Component
@Transactional
public class ActionService extends BaseService {

	private ActionDAO actionDAO;

	@Resource
	public void setActionDAO(ActionDAO actionDAO) {
		this.actionDAO = actionDAO;
	}
	
	/*根据条件查找*/
	public List findByHql(String hql,Object[] values) throws Exception {
		return actionDAO.findByHql(hql, values);
	}
	
	/*根据条件查找*/
	public List findByHql(String hql,Object value) throws Exception {
		return actionDAO.findByHql(hql, value);
	}
	
	/*根据角色删除权限*/
	public void deleteByRoleId(Integer roleId) throws Exception {
		actionDAO.executeHQL("delete from Action where roleId=?", new Object[]{roleId});
	}
	
	/*根据HQL删除权限*/
	public void deleteByHql(String hql) throws Exception {
		actionDAO.exec(hql);
	}
	
	/*保存多个权限*/
	public void saveOrUpdateList(List actionList) throws Exception {
		actionDAO.saveOrUpdateAll(actionList);
	}
	
	/*查找角色权限类型*/
	public Integer getActionType(Integer roleId,String actionKey) throws Exception {
		List list=actionDAO.findByHql("select actionType from Action where roleId=? and actionKey=?", new Object[]{roleId,actionKey});
		return (Integer)list.get(0);
	}
	
	/*登录成功后赋予用户权限*/
	public void setUserAction(User user,HttpServletRequest request) throws Exception {
		String roleId=user.getRoleId();
		List menuActionList=actionDAO.findByHql("select actionKey from Action where roleId in ("+roleId+") and actionType=0");
		List buttonActionList=actionDAO.findByHql("select actionKey from Action where roleId in ("+roleId+") and actionType=1");
		StringBuffer actionUrl=new StringBuffer();
		if(menuActionList!=null && menuActionList.size()>0){
			for(int i=0;i<menuActionList.size();i++){
				if(menuActionList.get(i)!=null){
					String actionKey=menuActionList.get(i).toString();
					if(i!=0)
						actionUrl.append("|");
					actionUrl.append(actionKey);
				}
			}
		}
		request.getSession().setAttribute("menuAction", menuActionList);
		request.getSession().setAttribute("buttonAction", buttonActionList);
		request.getSession().setAttribute("actionUrl", actionUrl.toString());
	}
}
